package com.digitalchina.lxnsy.activity.old;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.adapter.ImagePickerAdapter;
import com.digitalchina.lxnsy.api.BusinessFile;
import com.digitalchina.lxnsy.api.BusinessHelpFeedback;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.FileVO;
import com.digitalchina.lxnsy.loader.GlideImageLoader;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.ui.ImagePreviewDelActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：郑皓
 * 创建时间：2018/3/14 17:53
 * 修改备注：
 * ================================================
 */
public class SendFeedbackActivity extends BaseActivity {

    @Bind(R.id.consult_issue_et_issue)
    EditText consultIssueEtIssue;
    @Bind(R.id.consult_issue_picture)
    RecyclerView consultIssuePicture;
    @Bind(R.id.consult_issue_btn_ask)
    Button consultIssueBtnAsk;

    // 图片
    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;
    private ImagePickerAdapter imagePickerAdapter;
    private ArrayList<ImageItem> selectedImageList; //当前选择的所有图片
    private int maxImgCount = 3;               //允许选择图片最大数
    private List<String> filePath = new ArrayList<>(); // 图片地址
    private String imgs = ""; // 图片 多张以逗号隔开
    private int imgNum = 0; // 标记传到第几张图

    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_send_feedback);
        setTitle("反馈");
    }

    @Override
    public void initMember() {

        // 图片
        selectedImageList = new ArrayList<>();
        imagePickerAdapter = new ImagePickerAdapter(this, selectedImageList, maxImgCount);

        consultIssuePicture.setLayoutManager(new GridLayoutManager(this, maxImgCount));
        consultIssuePicture.setHasFixedSize(true);
        consultIssuePicture.setAdapter(imagePickerAdapter);

    }

    @Override
    public void addListener() {

        // 图片
        imagePickerAdapter.setOnItemClickListener(new ImagePickerAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                switch (position) {
                    case IMAGE_ITEM_ADD:
                        //打开选择,本次允许选择的数量
                        ImagePicker imagePicker = ImagePicker.getInstance();
                        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
                        imagePicker.setShowCamera(true);  //显示拍照按钮
                        imagePicker.setCrop(false);        //允许裁剪（单选才有效）
                        imagePicker.setMultiMode(true);    //是否多选模式
                        imagePicker.setSelectLimit(maxImgCount - selectedImageList.size()); //选中数量限制
                        Intent intent = new Intent(SendFeedbackActivity.this, ImageGridActivity.class);
                        startActivityForResult(intent, REQUEST_CODE_SELECT);
                        break;
                    default:
                        //打开预览
                        Intent intentPreview = new Intent(SendFeedbackActivity.this, ImagePreviewDelActivity.class);
                        intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) imagePickerAdapter.getImages());
                        intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                        startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                        break;
                }
            }
        });

        consultIssueBtnAsk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String issue = consultIssueEtIssue.getText().toString();
                if (StringUtil.isStrEmpty(issue) || issue.length() < 4) {
                    showToast("请填写不低于4个字的问题描述");
                    return;
                }

                imgNum = 0;
                // 先上传图片
                if (filePath.size() <= 0)
                    BusinessHelpFeedback.addFeedBack(SendFeedbackActivity.this, consultIssueEtIssue.getText().toString(), imgs, mHandler);
                else {
                    showDialog("正在发送...");
                    BusinessFile.imageCompressAndUpload(SendFeedbackActivity.this, filePath.get(imgNum), mHandler);
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                for (int i = 0; i < images.size(); i++) {
                    filePath.add(images.get(i).path);
                }
                selectedImageList.addAll(images);
                imagePickerAdapter.setImages(selectedImageList);
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                filePath.clear();
                selectedImageList.clear();
                selectedImageList.addAll(images);
                for (int i = 0; i < images.size(); i++) {
                    filePath.add(images.get(i).path);
                }
                imagePickerAdapter.setImages(selectedImageList);
            }
        }
    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case MSG.MSG_FILE_UPLOAD_SUCCESS: // 上传图片
                        imgNum++;
                        FileVO fileVO = FastJsonUtil.getBean(msg.obj.toString(), "body", "fileStorage", FileVO.class);
                        imgs += fileVO.getName() + ";";
                        if (imgNum < filePath.size()) {
                            BusinessFile.imageCompressAndUpload(SendFeedbackActivity.this, filePath.get(imgNum), mHandler);
                        } else {
                            BusinessHelpFeedback.addFeedBack(SendFeedbackActivity.this, consultIssueEtIssue.getText().toString(), imgs, mHandler);
                        }
                        break;
                    case MSG.MSG_FILE_UPLOAD_FIELD:
                        dismissDialog();
                        showToast(msg.obj.toString() + "");
                        break;
                    case MSG.MSG_ADD_FEEDBACK_SUCCESS:
                        dismissDialog();
                        new MaterialDialog.Builder(SendFeedbackActivity.this)
                                .title("反馈成功")
                                .content("感谢您对农科专家的关注与支持，我们会认真处理您的反馈，尽快修复和完善相关功能。")
                                .positiveText("确定")
                                .cancelable(false)
                                .canceledOnTouchOutside(false)
                                .onPositive(new MaterialDialog.SingleButtonCallback() {
                                    @Override
                                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                        finish();
                                    }
                                })
                                .show();
                        break;
                    case MSG.MSG_ADD_FEEDBACK_FIELD:
                        dismissDialog();
                        showToast(msg.obj.toString() + "");
                        break;
                }
            }
        };
    }

    @Override
    public void callBack(Object object) {

    }

    @Override
    public void rightOnClick() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
